package managedbean.CRM.Employee;

import entity.Employee;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import javaclass.RandomString;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import manager.EmailManager;
import session.stateless.EmployeeBeanLocal;

@ManagedBean
@ViewScoped

public class EditEmployeeManagerBean implements Serializable
{
    @EJB
    private EmployeeBeanLocal employeeSessionBeanLocal;
    private Employee employeeToEdit;
    private String statusMessage;
    private String enteredPassword;
    private String activatedStatusStr;    
    
    public EditEmployeeManagerBean() {}
    
    public Employee getEmployeeToEdit() {
        return employeeToEdit;
    }
    public void setEmployeeToEdit(Employee employeeToEdit) {
        this.employeeToEdit = employeeToEdit;
    }

    public String getStatusMessage() {
        return statusMessage;
    }
    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public String getActivatedStatusStr() {
        return activatedStatusStr;
    }

    public void setActivatedStatusStr(String activatedStatusStr) {
        this.activatedStatusStr = activatedStatusStr;
    }
        
    public void initView(PhaseEvent event){
        if(employeeToEdit == null)
        {            
            employeeToEdit = (Employee)FacesContext.getCurrentInstance().getExternalContext().getFlash().get("selectedEmployee");            if (employeeToEdit.getActivatedStatus()){
                this.activatedStatusStr = "activate";
            }
            else{
                this.activatedStatusStr = "deactivate";
            }
        }
    }
    
    public void updateExistingEmployee(ActionEvent event)
    {
        
        String temp_ActivatedStatusStr = String.valueOf(activatedStatusStr);
        if (temp_ActivatedStatusStr.equals("activate")){
            employeeToEdit.setActivatedStatus(true);
        }
        else{
            employeeToEdit.setActivatedStatus(false);
        }
        try{
            employeeSessionBeanLocal.updateEmployee(employeeToEdit.getEmployeeId(), employeeToEdit.getUserName(), employeeToEdit.getEmployeeName(), employeeToEdit.getEmployeeNRIC(), employeeToEdit.getEmployeeEmail(), employeeToEdit.getEmployeeContactNumber(), employeeToEdit.getEmployeeAddress(), employeeToEdit.getAttempt(), employeeToEdit.getActivatedStatus(), employeeToEdit.getPosition().getId());        
            statusMessage = "Employee IS Updated Successfully."; 

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,  "Update Employee Result: " +statusMessage+"", "")); 
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }  
    
    public void resetPassword(ActionEvent event){
        try{
            RandomString rs = new RandomString();
            String tempPassword = rs.RandomStringWithLength(6);
            employeeSessionBeanLocal.resetPassword(employeeToEdit.getEmployeeId(), tempPassword);
            statusMessage = "Employee's Password Is Reset Successfully."; 

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,  "Reset Password Employee Result: " + statusMessage, "")); 
            EmailManager emailManager = new EmailManager();             
            emailManager.setEmailAddress(employeeToEdit.getEmployeeName(), employeeToEdit.getEmployeeEmail());
            String subject = "Account's Password at Merlion's ERP System was reset.";
            String content = "Your account's password was reset by administrator.\n"
                    + "You can reset your password using system auto-generated password:\n"
                    + tempPassword;
            emailManager.sentEmail(subject, content);             
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void validateNRIC(FacesContext context, UIComponent toValidate, Object value){
        
        String NRIC = (String) value;
        String[] temp_array = {"S", "F", "T", "G"};
        ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(temp_array));
        String prefix = NRIC.trim().substring(0,1);
        boolean check = true;
        if (!arrayList.contains(prefix))
        {
            check = false;
        }

        if (NRIC.length() != 9)
            check = false;
        else{
            try
            {
                Integer t = (Integer.parseInt(NRIC.substring(1,8)));
            }
            catch (NumberFormatException nfe)
            {
                check = false;
            }
        }
        if (!check) {
            ((UIInput)toValidate).setValid(false);
            FacesMessage message = new FacesMessage("NRIC is not correct. Please re-enter.");
            message.setSeverity(FacesMessage.SEVERITY_WARN);
            context.addMessage(toValidate.getClientId(context), message);
        }
    }    
    
     public void validateEmail(FacesContext context, UIComponent toValidate, Object value){
        
        String email = (String) value;
        boolean check = true;
        if (!email.contains("@"))
        {
            check = false;
        }
        else
        {
            int index = email.indexOf("@");
            String substring = email.substring(index+1);
            if ((substring.contains("@")) || (!substring.contains(".")))
            {
                check = false;
            }
        }
        if (!check) {
            ((UIInput)toValidate).setValid(false);
            FacesMessage message = new FacesMessage("Email is not correct. Please re-enter.");
            message.setSeverity(FacesMessage.SEVERITY_WARN);
            context.addMessage(toValidate.getClientId(context), message);
        }
    }   
     
     public void validateContactNumber(FacesContext context, UIComponent toValidate, Object value){
        
        String contactNumber = (String) value;
        boolean check = true;
        Integer temp = 0;
        int count = 1;
        try 
        {
            temp = Integer.parseInt(contactNumber);
        }
        catch (NumberFormatException nfe)
        {
            check = false;
        }
        
        int div = 10;
        while (temp / div > 0)
        {
            div *=10;
            count+=1;
        }
        if ((count > 15) || (count < 8))
        {
            check = false;
        }
        if (!check) {
            ((UIInput)toValidate).setValid(false);
            FacesMessage message = new FacesMessage("Contact number is not correct. Please re-enter.");
            message.setSeverity(FacesMessage.SEVERITY_WARN);
            context.addMessage(toValidate.getClientId(context), message);
        }
    }        

     public void validateAttemp(FacesContext context, UIComponent toValidate, Object value){
        boolean check = true;
        long attemp = 0;
        try{
            attemp = (Long) value;
        }
        catch (NumberFormatException nfe)
        {
            check = false;
        }       
        if (attemp < -1)
        {
            check = false;
        }
        if (!check) {
            ((UIInput)toValidate).setValid(false);
            FacesMessage message = new FacesMessage("Attempt is not correct. Please re-enter.");
            message.setSeverity(FacesMessage.SEVERITY_WARN);
            context.addMessage(toValidate.getClientId(context), message);
        }
    }          
}
